package com.songyang.blog.util;

import com.songyang.blog.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ShiroUtils {

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    /**
     * 获取授权凭证
     */
    public static Subject getSubject() {
        //设置session过期
//        SecurityUtils.getSubject().getSession().setTimeout(1000*10);
        return SecurityUtils.getSubject();
    }

    /**
     * 通过shiro凭证获取用户对象
     */
    public static User getUser() {
        Subject subject = SecurityUtils.getSubject();
        Object object = subject.getPrincipal();
        return (User) object;
    }

    public static void updateUser(User userInfo) {

        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection =
                new SimplePrincipalCollection(userInfo, realmName);
        subject.runAs(newPrincipalCollection);

    }

    public static Long getUserId() {
        return getUser().getId();
    }

    /**
     * 用户退出
     */
    public void logout() {
        Cookie[] cookies = request.getCookies();
//        System.out.println("之前"+cookies.length);
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("isLogin")) {
                Cookie cookie = new Cookie("isLogin", "");
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            } else if (cookies[i].getName().equals("isLoginUn")) {
                Cookie cookie = new Cookie("isLoginUn", "");
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            } else if (cookies[i].getName().equals("time")) {
                Cookie cookie = new Cookie("time", "");
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        getSubject().logout();//shiro退出
    }
}
